package com.cos.shop.dao.impl;

import com.cos.shop.dao.ItemDao;
import com.cos.shop.entity.Item;
import com.cos.shop.entity.Product;
import com.cos.shop.util.JDBCUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: COS
 * @time: 2022/2/25 10:39
 * @description:
 */
public class ItemDaoImpl implements ItemDao {
    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public List<Item> getItemsByOid(String oid) throws SQLException, InvocationTargetException, IllegalAccessException {
        List<Map<String, Object>> query = qr.query("select i.iid, i.oid, i.pid, i.icount, i.inum,p.pname,p.pprice,p.pstate," +
                        "p.pimage,p.pinfo,p.ptime from item i,product p where i.pid=p.pid and i.oid = ?",
                new MapListHandler(), oid);

        if (query!=null&&query.size()>0) {
            List<Item> itemList = new ArrayList<>();
            for (Map<String, Object> map : query) {
                //创建需要封装数据的对象
                Item i = new Item();
                Product p = new Product();
                //工具类
                BeanUtils.populate(i, map);
                BeanUtils.populate(p, map);
                //手动封装对象
                i.setPro(p);
                //把对象加入到list集合
                itemList.add(i);
            }
            //返回集合数据
            return itemList;
        }
        return null;
    }

    @Override
    public int[] addItems(List<Item> itemList) throws SQLException {
        //iid	oid	pid	icount	inum
        //11	20201212100232931	21	20.00	1
        //11	20201212100232931	21	20.00	1
        //11	20201212100232931	21	20.00	1
        //11	20201212100232931	21	20.00	1
//        qr.update()
        //创建二维数据 设置高维数组的长度为list大小
        Object[][] items=new Object[itemList.size()][];
        //遍历集合把数据转到二维数组的低微数组
        for (int i = 0; i < itemList.size(); i++) {
            Item item = itemList.get(i);
            items[i]=new Object[]{item.getOid(),item.getPid(),item.getIcount(), item.getInum()};
        }
        //编写sql语句
        String sql = "insert into item values (default,?,?,?,?)";
        //调用批量操作
        int[] batch = qr.batch(sql, items);
        return batch;
    }
}
